package vn.kiemviec.app.task;

import java.util.ArrayList;

import org.w3c.dom.Element;

import vn.kiemviec.app.api.ApiSettings;
import vn.kiemviec.app.data.IndustryEntry;
import vn.kiemviec.app.utils.LogTools;
import vn.kiemviec.app.utils.XmlUtils;


import android.os.AsyncTask;


public class GetIndustryTask extends AsyncTask<Object, Object, Object> {

	public interface OnGetIndustryListener{
		public void onSuccessfull(ArrayList<IndustryEntry> listEntry);
		public void onError(int error);
	}
	
	private OnGetIndustryListener mHandler;
	private ArrayList<IndustryEntry> mList;
	private boolean IsSuccessful;
	
	public void setOnIndustryListener(OnGetIndustryListener ev){
		mHandler = ev;
	}
	
	@Override
	protected Object doInBackground(Object... params) {
		// TODO Auto-generated method stub
		try {
			
			LogTools.info("***begin access:"+ApiSettings.getIndustryUrl());
			Element root = XmlUtils.getXmlRootByUrl(ApiSettings.getIndustryUrl());
			String status = root.getElementsByTagName("status").item(0).getTextContent();
			if(status.endsWith("success")){
				String data = root.getElementsByTagName("response").item(0).getTextContent();
				mList = IndustryEntry.getListFromJson(data);
				IsSuccessful = true;
			}else{
				IsSuccessful = false;
			}

			LogTools.info("***end access sucessfull:"+ApiSettings.getIndustryUrl());
		} catch (Exception e) {
			// TODO: handle exception
			LogTools.error(e.toString());
			IsSuccessful = false;
			LogTools.error("***end access with error:"+ApiSettings.getIndustryUrl());
			if(mHandler != null) mHandler.onError(0);
		}
		
		return null;
	}

	@Override
	protected void onPostExecute(Object result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		if(IsSuccessful){
			if(mHandler != null) mHandler.onSuccessfull(mList);
		}		
	}
}
